﻿using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using CodeMan.RabbitMq.Base.RabbitMq.Config;

namespace CodeMan.RabbitMq.Base.RabbitMq.Producer
{
    /// <summary>
    /// 生产者实现类
    /// </summary>
    public class RabbitProducer : IRabbitProducer
    {
        private readonly RabbitConnection _connection;

        public RabbitProducer(RabbitConnection connection)
        {
            _connection = connection;
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="exchange">交换机</param>
        /// <param name="routingKey">路由KEY</param>
        /// <param name="dto">发送消息对象</param>
        public void Publish<T>(string exchange, string routingKey, T dto) where T : new()
        {
            this.Publish(exchange, routingKey, JsonConvert.SerializeObject(dto));
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="exchange">交换机</param>
        /// <param name="routingKey">路由KEY</param>
        /// <param name="content">发送消息内容</param>
        public void Publish(string exchange, string routingKey, string content)
        {
            var channel = _connection.GetConnection().CreateModel();
            var prop = channel.CreateBasicProperties();//定义消息的参数
            channel.BasicPublish(exchange, routingKey, false, prop, Encoding.UTF8.GetBytes(content));
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="exchange">交换机</param>
        /// <param name="routingKey">路由KEY</param>
        /// <param name="props">参数</param>
        /// <param name="dto">发送消息对象</param>
        public void Publish<T>(string exchange, string routingKey, IDictionary<string, object> props, T dto) where T : new()
        {
            this.Publish(exchange, routingKey, props, JsonConvert.SerializeObject(dto));
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="exchange">交换机</param>
        /// <param name="routingKey">路由KEY</param>
        /// <param name="props">参数</param>
        /// <param name="content">发送消息内容</param>
        public void Publish(string exchange, string routingKey, IDictionary<string, object> props, string content)
        {
            var channel = _connection.GetConnection().CreateModel();
            var prop = channel.CreateBasicProperties();//定义消息的参数
            if (props != null && props.ContainsKey("x-delay"))
            {
                //如果不设TTL，表示消息永远不会过期；如果设置为“0”表示除非此时可以直接投递该消息到消费者中，否则该消息将会直接被丢弃掉；
                prop.Expiration = props["x-delay"].ToString();//用于延时队列，给每条消息设置“x-message-ttl”过期时间(单位：毫秒)                
            }
            channel.BasicPublish(exchange, routingKey, false, prop, Encoding.UTF8.GetBytes(content));
        }
    }
}